import React, { Component } from 'react';
import { Table, Space, Button, Breadcrumb, Form, Upload, Modal, Pagination, message, Select, Radio, Checkbox } from 'antd';
import { AppstoreTwoTone, PlusOutlined, FormOutlined, DeleteOutlined, } from '@ant-design/icons'
import styles from './common.less'
import { connect } from 'dva'
import TextArea from 'antd/lib/input/TextArea';
import * as requesturl from "@/services/request-url";

const { Option } = Select
const CheckboxGroup = Checkbox.Group;
@connect()
class StandardDataForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
            form: {},
            releaseTime: "",
            endTime: "",
            effectDate: "",
            tableloading: false,
            loading: false,
            modalTitle: "新增标准数据",
            isModalVisible: false,
            currentPage: 1,
            pageSize: 10,
            data: [],//表格数据
            standardDataId: "",//标准记录id
            standardMetaData: [],//标准元数据
            optionForm: {},//所有选择项数据
            radioValue: 1,//单选值
            CheckboxValue: [],//多选
            selectValue: "",
            submitKv: [],//提交的kv值
            textValue: "",//文本
            selectOption: {},//下拉
            isEdit: false,//新增 or 编辑
            receiveStandardId: "",//标准id
            uploadFileList: [],
            importExcelData: [] //导入所需数据
        }
        //表头 标准中的所有字段
        this.columns = [];
    }

    componentDidMount = () => {
        // console.log(this.props.location.standardId)
        let receiveStandardId = ""
        if (this.props.location.standardId) {//判断当前有参数
            receiveStandardId = this.props.location.standardId;
            sessionStorage.setItem('standardId', receiveStandardId);// 存入到sessionStorage中
        } else {
            receiveStandardId = sessionStorage.getItem('standardId');// 当state没有参数时，取sessionStorage中的参数
        }
        this.setState({
            receiveStandardId: receiveStandardId
        },
            () => {
                this.getStandardMetaList()
                this.getOptionDatas()
            })
    }
    //获取列表数据
    getStandardDataList = () => {
        this.props.dispatch({
            type: "global/getStandDetailInfoList",
            payload: {
                id: this.state.receiveStandardId
            }
        }).then(res => {
            console.log("表数据", res)
            if (res.data) {
                let dataObj = {}
                let DATA = []
                res.data && res.data.map(item1 => {//所有记录
                    let standardRowDataId = item1.id
                    console.log(standardRowDataId)
                    item1.kv.map((item, index) => {//每条记录的遍历
                        let NAME = ""
                        console.log(item, this.state.optionForm)
                        this.state.optionForm[`List${item.bdId}`] && this.state.optionForm[`List${item.bdId}`].map(item => {
                            console.log(item)
                        })
                        dataObj = {//表格数据
                            ...dataObj,
                            [item.name]: item.content,
                            [`${item.name}text`]: item.contentValue,
                            // key: index*0.1,
                            standardRowDataId,

                        }
                    })
                    DATA.push(dataObj)
                })
                this.setState({
                    data: DATA,
                    tableloading: true
                })
            }
        })
    }
    //获取元数据列表
    getStandardMetaList = () => {
        this.props.dispatch({
            type: "global/getBasicFieldInfoList",
            payload: {
                id: this.state.receiveStandardId
            }
        }).then(res => {
            if (res) {
                console.log("元数据", res)
                let imptArr = []
                res.data && res.data.map((item, index) => {
                    //导入所需数组
                    imptArr.push(item.id)
                    let obj = {//表头
                        title: item.name,
                        key: index,
                        dataIndex: `${item.name}text`,
                        align: "center",
                        width: 100
                    }
                    this.columns.push(obj)
                    console.log("表头+1")
                })
                this.columns.push(
                    {
                        title: '操作',
                        key: 'action',
                        align: "center",
                        fixed: 'right',
                        width: 150,
                        render: (text, record, index) => (
                            <Space size="small">
                                <Button type="link"
                                    icon={<FormOutlined />}
                                    size="small"
                                    onClick={() => this.handleEdite(record)}>编辑</Button>
                                <Button type="link"
                                    icon={<DeleteOutlined />}
                                    danger
                                    size="small"
                                    onClick={() => this.handleDelete(record)}>删除</Button>
                            </Space>
                        ),
                    },
                )
                this.getStandardDataList()

                this.setState({
                    standardMetaData: res.data,
                    importExcelData: imptArr
                })
            }
        })
    }
    //选择项详情
    getOptionDatas = () => {
        this.columns.map((item) => {
            this.getOption(item.metaId)
        })

    }
    getOption = (id) => {
        this.props.dispatch({
            type: "global/getBasicFieldOptionInfoById",
            payload: {
                id: id
            }
        }).then(res => {
            let params = `List${id}`
            this.setState({
                optionForm: {
                    ...this.state.optionForm,
                    [params]: res.data
                },
            }, () => { console.log(this.state.optionForm) })
        })
    }
    //新增
    createEvent = (params) => {
        const { standardMetaData } = this.state
        console.log(this.columns)
        console.log(standardMetaData)
        standardMetaData.map(item1 => {
            this.columns.map(item2 => {
                if (item2.title === item1.name) {
                    item2.type = item1.typeName
                    item2.metaId = item1.id
                    // item2.metaName=item1.name
                }
            })
        })
        console.log(this.columns)
        this.getOptionDatas()
        this.setState({
            isModalVisible: true,
            selectValue: "",
            CheckboxValue: [],//多选
            radioValue: 0,//单选值
            standardDataId: "",
            isEdit: false,
            submitKv: [],
            form: {}
        })
    }
    //获取详情
    getStandardDetail = (detailId) => {
        this.props.dispatch({
            type: "global/getStandDetailInfo",
            payload: {
                id: detailId
            }
        }).then(res => {
            console.log(res)
            if (res) {
                this.setState({
                    submitKv: res.data.kv
                })
            }
        })
    }
    //编辑
    handleEdite = (record) => {
        console.log(record)
        this.getStandardDetail(record.standardRowDataId)
        console.log(this.state.standardMetaData)
        // let obj={}
        // this.state.submitKv && this.state.submitKv.map((item, index) => {
        //     this.state.optionForm[`List${item.bdId}`].map(item2=>{
        //         let arr=item.content.split(",").map(Number)
        //         arr.map(item3=>{
        //             if(item3===item2.id){
        //                 obj[item.name]=`${item2.name},${obj[item.name]}`
        //             }
        //         })
        //     })
        // })
        // this.setState({
        //     form:obj
        // },()=>{console.log(this.state.form)})
        const { standardMetaData } = this.state
        standardMetaData.map(item1 => {
            this.columns.map(item2 => {
                if (item2.title === item1.name) {
                    item2.type = item1.typeName
                    item2.metaId = item1.id
                    // item2.metaName=item1.name
                }
            })
        })
        console.log(this.columns)
        this.getOptionDatas()
        this.setState({
            isModalVisible: true,
            modalTitle: "编辑标准数据",
            standardDataId: record.standardRowDataId,
            isEdit: true,
            form: record
        })
    }
    //详细标准删除
    handleDelete = (record) => {
        console.log(record)
        this.props.dispatch({
            type: "global/deleteStandDetailInfo",
            payload: {
                id: record.standardRowDataId
            }
        }).then(res => {
            console.log(res)
            message.success("删除成功！")
            this.getStandardDataList()
        })
    }
    //新增编辑表单提交
    handleSubmit = () => {
        console.log(this.state.submitKv)

        this.props.dispatch({
            type: "global/saveStandDetailInfo",
            payload:
                this.state.standardDataId !== "" ?
                    {
                        id: this.state.standardDataId,
                        stId: this.state.receiveStandardId,
                        kv: this.state.submitKv
                    }
                    :
                    {
                        stId: this.state.receiveStandardId,
                        kv: this.state.submitKv
                    }
        }).then(res => {
            console.log(res)
            message.success("更新成功！")
            this.getStandardDataList()
        })
        this.setState({ isModalVisible: false })

    }
    //校验失败
    onFinishFailed = () => {
        console.log("onfinishfaild")
    }
    //关闭弹窗、
    handleCancel = (params) => {
        this.setState({ isModalVisible: false })
    }
    //增加编辑弹框表单改变
    //文本  文本域
    handleTextChange = (e, value) => {
        let { form, isEdit, submitKv } = this.state
        console.log(value, form)
        console.log(e.target.value)
        this.setState({
            ftextValue: e.target.value
        })
        let ishave = false
        if (submitKv.length > 0) {
            submitKv.map((item) => {
                if (item.bdId === value.metaId) {
                    console.log("已存在")
                    ishave = true
                    item.content = e.target.value
                }
            })
        } else {
            let obj = {
                bdId: value.metaId,
                // id: "",
                name: value.title,
                sort: "1",
                content: e.target.value
            }
            if (isEdit) obj.id = value.id
            this.setState({
                submitKv: [obj, ...this.state.submitKv]
            }, () => { console.log(this.state.submitKv) })
        }
        if (!ishave) {
            let obj = {
                bdId: value.metaId,
                // id: "",
                name: value.title,
                sort: "1",
                content: e.target.value
            }
            if (isEdit) obj.id = value.id
            this.setState({
                submitKv: [obj, ...this.state.submitKv]
            }, () => { console.log(this.state.submitKv) })
        }
    }

    //下拉
    handleSelectChange = (val, option, value) => {
        console.log(val, option, value)
        console.log(this.state.standardMetaData)
        this.setState({
            selectOption: option
        })
        let ishave = false
        console.log(this.state.selectOption)

        if (this.state.submitKv.length > 0) {
            this.state.submitKv.map((item) => {
                if (item.bdId === value.metaId) {
                    console.log("已存在")
                    ishave = true
                    item.content = option.value
                    console.log(this.state.submitKv)
                }
            })
        } else {
            console.log("不存在")
            let obj = {
                bdId: value.metaId,
                // id: option.value,
                name: value.title,
                sort: "1",
                content: option.value
            }
            if (this.state.isEdit) obj.id = value.id
            this.setState({
                submitKv: [obj, ...this.state.submitKv]
            }, () => { console.log(this.state.submitKv) })
        }
        // if (!ishave) {
        //     let obj = {
        //         bdId: value.metaId,
        //         // id: option.value,
        //         name: value.title,
        //         sort: "1",
        //         content: option.children
        //     }
        //     this.setState({
        //         submitKv: [ obj, ...this.state.submitKv ]
        //     }, () => { console.log(this.state.submitKv) })
        // }
    }

    //单选
    handleRadioChange = (e, val) => {
        console.log(e.target.value, val)
        console.log(this.state.optionForm)
        this.setState({ radioValue: e.target.value })
        let param = `List${val.metaId}`
        let radioName = ""
        let ishave = false
        this.state.optionForm[param] && this.state.optionForm[param].map(item => {
            if (item.id === e.target.value) {
                radioName = item.name
            }
        })

        if (this.state.submitKv.length > 0) {
            this.state.submitKv.map((item) => {
                if (item.bdId === val.metaId) {
                    console.log("已存在")
                    ishave = true
                    item.content = e.target.value
                    console.log(this.state.submitKv)
                }
            })
        } else {
            let obj = {
                bdId: val.metaId,
                // id: e.target.value,
                name: val.title,
                sort: "1",
                content: e.target.value
            }
            if (this.state.isEdit) obj.id = val.id
            this.setState({
                submitKv: [obj, ...this.state.submitKv]
            }, () => { console.log(this.state.submitKv) })
        }
        if (!ishave) {
            let obj = {
                bdId: val.metaId,
                // id: e.target.value,
                name: val.title,
                sort: "1",
                content: e.target.value
            }
            if (this.state.isEdit) obj.id = val.id
            this.setState({
                submitKv: [obj, ...this.state.submitKv]
            }, () => { console.log(this.state.submitKv) })
        }

    }
    //多选
    handleCheckboxChange = (checkedValues, val) => {
        console.log(checkedValues, val)
        this.setState({
            CheckboxValue: checkedValues
        })
        let param = `List${val.metaId}`
        let checkName = []
        let ishave = false
        console.log(param)
        this.state.optionForm[param] && this.state.optionForm[param].map(item => {
            checkedValues.map(item2 => {
                if (item.id === item2) {
                    checkName.push(item.name)
                }
            })
        })

        if (this.state.submitKv.length > 0) {
            this.state.submitKv.map((item) => {
                if (item.bdId === val.metaId) {
                    console.log("已存在")
                    ishave = true
                    item.content = checkedValues.join(",")
                    console.log(this.state.submitKv)
                }
            })
        } else {
            let obj = {
                bdId: val.metaId,
                // id: checkedValues.join(","),
                name: val.title,
                sort: "1",
                content: checkedValues.join(",")
            }
            if (this.state.isEdit) obj.id = val.id
            this.setState({
                submitKv: [obj, ...this.state.submitKv]
            }, () => { console.log(this.state.submitKv) })
        }
        if (!ishave) {
            let obj = {
                bdId: val.metaId,
                // id: checkedValues.join(","),
                name: val.title,
                sort: "1",
                content: checkedValues.join(",")
            }
            if (this.state.isEdit) obj.id = val.id
            this.setState({
                submitKv: [obj, ...this.state.submitKv]
            }, () => { console.log(this.state.submitKv) })
        }
    }
    //
    handleFormValuesChange = (changedValues, allValues) => {
        console.log(changedValues, allValues)
    }
    //模板导出
    fileDownload = () => {
        this.props.dispatch({
            type: "global/downloadStandModel",
            payload: {
                id: this.state.receiveStandardId
            }
        })
            .then(blob => {
                console.log("文件流", blob);
                // let filename = fileUrl.split("/")[fileUrl.split("/").length - 1]
                // // let filename = decodeURI(headers["content-disposition"].split(";")[1].split("filename=")[1]);
                // let blob = new Blob(['\uFEFF' +data])
                // console.log("blob对象",blob);
                const link = document.createElement('a')
                link.download = "标准模板"
                link.style.display = 'none'
                link.href = URL.createObjectURL(blob)
                document.body.appendChild(link)
                link.click()
                URL.revokeObjectURL(link.href)
                document.body.removeChild(link)
            });
    }
    //模板导入
    handleFileUpload = ({ file, fileList }) => {
        console.log({ file, fileList })
        if (file.response && file.response.code === "403") {
            let a = document.createElement("a")
            a.href = `${requesturl.login}/cas/jwt/login.do`;
            a.click();
        }
        if (file.status == 'done') {
            if(file.response.code == '1') {
                message.success("导入成功")
            }else{
                message.error("导入失败")
            }
            
        }
        
    }

    render() {
        let { data, isModalVisible, modalTitle, form, selectValue, radioValue, CheckboxValue } = this.state;

        return (
            <div>
                <div className={styles.pagetop}>
                    <span className={styles.pageheader}>
                        <Breadcrumb>
                            <Breadcrumb.Item><AppstoreTwoTone />标准与规范</Breadcrumb.Item>
                            <Breadcrumb.Item>
                                <a href="/assetstandard/standardList">标准列表</a>
                            </Breadcrumb.Item>
                            <Breadcrumb.Item>
                                <a href="/assetstandard/StandardData">标准数据列表</a>
                            </Breadcrumb.Item>
                        </Breadcrumb>
                    </span>
                </div>
                <div style={{ background: "white" }}>
                    <div style={{ padding: "10px 0" }}>
                        <Button type="primary"
                            icon={<PlusOutlined />}
                            style={{ marginLeft: "20px" }}
                            onClick={this.createEvent}>新增</Button>
                        <Button type="primary"
                            style={{ marginLeft: "20px", marginRight: "20px" }}
                            onClick={this.fileDownload}>模板导出</Button>
                        <Upload
                            accept=".xls, .xlsx"
                            action={`${requesturl.importExcel}`}
                            data={file => ({
                                id: this.state.receiveStandardId,
                                basicId: this.state.importExcelData.join(","),
                                // file: file
                            })}
                            maxCount={1}
                            onChange={this.handleFileUpload}
                            showUploadList={false}>
                            <Button type="primary" style={{ width: "100%" }}>模板导入</Button>
                        </Upload>
                    </div>
                    {
                        this.state.tableloading ?
                            <Table
                                columns={this.columns}
                                dataSource={data}
                                pagination={false}
                                scroll={{ x: 800 }}
                            /> : null
                    }
                </div>
                {/* <div className={ styles.pagination }>
                    <Pagination
                        total={ data.length }
                        showSizeChanger
                        showQuickJumper
                        showTotal={ total => `共 ${total} 条` }
                        onChange={ this.pageChange }
                        onShowSizeChange={ this.pageSizeChange }
                    />
                </div> */}
                {
                    isModalVisible ?
                        <Modal
                            title={modalTitle}
                            centered
                            destroyOnClose={true}
                            okText="保存"
                            width={400}
                            visible={isModalVisible}
                            footer={false}
                            onCancel={this.handleCancel}
                        >
                            <Form name="form" style={{ marginLeft: "10%" }} >
                                {
                                    this.columns.map((item, index) => {
                                        let param = `List${item.metaId}`.replace("\"", "")
                                        let VALUE = form[item.title]
                                        console.log(VALUE)

                                        let VALUES = []
                                        if (VALUE) VALUES = VALUE.split(",").map(Number);
                                        // this.state.optionForm[ param ].map(item=>{
                                        //     if(item.id==VALUE)
                                        // })
                                        return (item.title !== "操作" ?
                                            <Form.Item key={index} label={item.title} rules={[{ required: true, message: `${item.title}不可为空.`, }]}>
                                                {
                                                    (item.type === "文本" || item.type === "文本域") ?
                                                        <TextArea
                                                            rows={1}
                                                            defaultValue={form[item.title]}
                                                            style={{ float: "left", width: "80%" }}
                                                            onChange={(e) => this.handleTextChange(e, item)} />
                                                        :
                                                        item.type === "下拉选" ?
                                                            <Select
                                                                defaultValue={this.state.isEdit ? VALUE * 1 : ""}
                                                                style={{ width: 220 }}
                                                                onChange={(value, option) => this.handleSelectChange(value, option, item)}
                                                            >
                                                                {
                                                                    this.state.optionForm[param] && this.state.optionForm[param].map((item, index) => {

                                                                        return <Option key={index} value={item.id}>{item.name}</Option>
                                                                    })
                                                                }
                                                            </Select>
                                                            :
                                                            item.type === "单选" ?
                                                                <Radio.Group
                                                                    onChange={(e) => this.handleRadioChange(e, item)}
                                                                    defaultValue={VALUE * 1}
                                                                >
                                                                    {
                                                                        this.state.optionForm[param] && this.state.optionForm[param].map((item, index) => {
                                                                            return <Radio key={index} value={item.id}>{item.name}</Radio>
                                                                        })
                                                                    }
                                                                </Radio.Group>
                                                                :
                                                                <Checkbox.Group defaultValue={VALUES} onChange={(checkedValue) => this.handleCheckboxChange(checkedValue, item)}>
                                                                    {
                                                                        this.state.optionForm[param] && this.state.optionForm[param].map((item, index) => {
                                                                            console.log(VALUES)
                                                                            return <Checkbox key={index} value={item.id}>{item.name}</Checkbox>
                                                                        })
                                                                    }
                                                                </Checkbox.Group>

                                                }
                                            </Form.Item>
                                            : null)
                                    })
                                }
                                <Form.Item>
                                    <Button
                                        type="primary"
                                        htmlType="submit"
                                        style={{ float: "right" }}
                                        onClick={this.handleSubmit}>保存</Button>
                                </Form.Item>
                            </Form>
                        </Modal> : ""
                }
            </div>
        );
    }
}

export default StandardDataForm;